<template>
	<view class="app app-bg">
		<view class="money">需付金额: ￥{{ vk.pubfn.priceFilter(money) }}</view>
		<view class="type">
			<text class="logo">选择支付方式</text>
			<view class="item" @tap="select('wxpay')">
				<image class="icon" src="@/static/mine/pay_weixin.png"></image>
				<text>微信支付</text>
				<image src="@/static/home/choose.png" v-if="type === 'wxpay'" class="selt"></image>
				<image src="@/static/home/choose_no.png" class="selt" v-else></image>
			</view>
			<view class="item" @tap="select('alipay')">
				<image class="icon" src="@/static/mine/pay_ali.png"></image>
				<text>支付宝支付</text>
				<image src="@/static/home/choose.png" v-if="type === 'alipay'" class="selt"></image>
				<image src="@/static/home/choose_no.png" class="selt" v-else></image>
			</view>
			<view class="item" @tap="select('balance')">
				<image class="icon" src="@/static/home/bal_pay.png"></image>
				<text>钱包支付</text>
				<text class="bal">余额: ￥{{ vk.pubfn.priceFilter(balance) }}</text>
				<image src="@/static/home/choose.png" v-if="type === 'balance'" class="selt"></image>
				<image src="@/static/home/choose_no.png" class="selt" v-else></image>
			</view>
		</view>
		<view class="btn" @tap="pay">立即支付</view>
		<u-modal content="还没有支付密码，请先前往设置" v-model="show"
			@confirm="vk.navigateTo('/pages/user/setting/update-payword')"></u-modal>
		<keyboard-pay ref="keyboard" :money="money" @finish="finish"></keyboard-pay>
		<vk-uni-pay ref="vkPay" :status.sync="vkPay.status" :code-url.sync="vkPay.codeUrl"
			:query-payment-action="vkPay.queryPaymentAction" :page-show="vkPay.pageShow" :polling="vkPay.polling"
			:return-url="vkPay.returnUrl"></vk-uni-pay>
		<!-- #ifdef H5 -->
		<!-- 二维码支付弹窗开始 -->
		<view class="pay-qrcode-popup" v-if="form1.provider !== 'vkspay' && vkPay.status < 2 && vkPay.codeUrl">
			<view class="pay-qrcode-popup-mask" @click="cancelPay"></view>
			<view class="pay-qrcode-popup-content">
				<vk-uni-qrcode :text="vkPay.codeUrl" :size="450"></vk-uni-qrcode>
				<view class="pay-qrcode-popup-info">
					<view>
						<text class="pay-qrcode-popup-info-fee">{{
							(form1.total_fee / 100).toFixed(2)
						}}</text>
						<text>元</text>
					</view>
					<view v-if="form1.provider == 'wxpay'">请用微信扫码支付</view>
					<view v-else-if="form1.provider == 'alipay'">请用支付宝扫码支付</view>
				</view>
				<button v-if="vkPay.status == 1" type="primary" @click="queryPayment">
					我已完成支付
				</button>
			</view>
		</view>
		<!-- 二维码支付弹窗结束 -->
		<!-- #endif -->

		<!-- VksPay个人支付二维码支付弹窗开始 -->
		<vk-uni-pay-qrcode-popup v-if="form1.provider === 'vkspay'" :provider="form1.provider"
			:provider-pay-method="form1.provider_pay_method" :status="vkPay.status" :code-url="vkPay.codeUrl"
			:qrcode-image="vkPay.qrcodeImage" :total-fee="form1.total_fee" :out-trade-no="form1.out_trade_no"
			@close="cancelPay" @afresh="afreshPayment" @query="queryPayment"></vk-uni-pay-qrcode-popup>
		<!-- VksPay个人支付二维码支付弹窗开始 -->
	</view>
</template>

<script>
	var vk = uni.vk // vk依赖
	import keyboardPay from "./components/keyboard-pay.vue"

	export default {
		components: {
			keyboardPay
		},
		data() {
			return {
				oid: "",
				money: 0,
				balance: 0,
				type: "wxpay",
				order_number: "",
				vkPay: {
					/**
					 * 查询支付状态的云函数配置
					 * 如果是非路由框架，则action为字符串，值为云函数名称
					 * 如果是路由框架，则按下方配置填写
					 */
					queryPaymentAction: {
						name: "vk-pay", // 云函数名称
						action: "pay/queryPayment", // 路由模式下云函数地址
						actionKey: "action", // 路由模式下云函数地址的识别key
						dataKey: "data" // 路由模式下云函数请求参数的识别key
					},
					// PC支付的付款二维码地址
					codeUrl: "",
					// 当前支付状态 0:等待发起支付 1:支付中 2:已支付
					status: 0,
					// 当前页面是否显示
					pageShow: true,
					// 启用轮询检测订单支付状态（仅h5支付有效）
					polling: true,
					// 微信手机外部浏览器H5支付时有效，必须是http或https开头的绝对路径，且在微信H5支付配置的域名白名单中。你还需要将此H5域名加入uniCloud白名单
					// 如果此值为空，则默认使用返回当前页面，返回的页面url参数会带上confirmShow=true&out_trade_no=实际订单号
					returnUrl: "",
					// 确认已支付的弹窗开关（微信手机外部浏览器H5支付时有效）
					confirmShow: false
				},
				// 表单请求数据
				form1: {
					provider: "wxpay",
					out_trade_no: "",
					openid: "", // 公众号支付必传，小程序支付可以不传
					total_fee: "", // 金额
					type: "goods" // 商品订单
				},

				flag: false,
				show: false
			}
		},
		onLoad(opt) {
			if (opt.id) {
				this.oid = opt.id
			} else {
				vk.toast("参数不足")
				return uni.navigateBack()
			}
			vk.showLoading("获取中...")
			this.options = opt
		},
		onReady() {
			let {
				options = {}
			} = this
			// 在onReady内执行是为了先让组件加载完成
			// 如果是同步回调过来的，执行下查询
			if (options.out_trade_no) {
				this.vkPay.status = 1
				this.$refs.vkPay._checkPay(options.out_trade_no, () => {
					this.paySuccess()
				})
			}
		},
		onShow() {
			this.init()
		},
		methods: {
			// 初始化
			init() {
				vk.callFunction({
					url: "client/order.queryOrderPay",
					data: {
						oid: this.oid
					}
				}).then(res => {
					this.flag = res.flag
					this.money = res.money
					this.balance = res.balance
					this.order_number = res.order_number
					vk.hideLoading()
				})
			},
			// 选择支付方式
			select(type) {
				this.type = type
			},
			// 立即支付
			pay() {
				if (!this.type) return vk.toast("请选择支付方式")
				if (this.type === "balance") {
					this.payForBalance()
				} else {
					this.payReal(this.type)
				}
			},
			// 余额支付
			payForBalance() {
				if (this.balance < this.money) return vk.toast("余额不足")
				if (!this.flag) {
					this.show = true
					return
				}
				this.$refs.keyboard.showPop(true)
			},
			finish(payword) {
				vk.callFunction({
					url: "client/order.payForBalance",
					title: "支付中...",
					data: {
						payword,
						oid: this.oid
					}
				}).then(() => {
					this.paySuccess()
				})
			},
			// 微信或支付宝支付
			payReal(type) {
				let {
					form1,
					vk
				} = this
				form1.out_trade_no = this.order_number
				form1.provider = type
				form1.total_fee = this.money
				let data = {
					provider: type,
					total_fee: this.money,
					out_trade_no: this.order_number
				}
				// #ifdef H5
				let aaa = vk.h5.getEnv()
				let bbb = vk.getStorageSync("openid")
				if (aaa === "h5-weixin" && bbb) data.openid = bbb
				data.return_url = window.location.href + "&out_trade_no=" + this.order_number
				// #endif
				this.$refs.vkPay.createPayment({
					action: {
						name: "router",
						dataKey: "data",
						actionKey: "$url",
						action: "client/order.createPaymentForService"
					},
					data,
					success: () => {
						this.paySuccess()
					},
					fail: res => {
						if (res.failType === "create") {
							vk.alert(res.msg)
						} else if (res.failType === "request") {
							vk.toast("请求支付失败")
						} else if (res.failType === "result") {
							vk.toast("支付失败")
						}
					},
					cancel: () => {
						vk.toast("用户取消支付")
					}
				})
			},
			// 支付成功
			paySuccess() {
				let pages = getCurrentPages()
				vk.toast("支付成功", "none", 800, () => {
					if (
						pages[pages.length - 2] &&
						pages[pages.length - 2].route == "pages/order/detail"
					) {
						// 订单详情支付返回原页面
						uni.$emit("paySuccess")
						vk.navigateBack()
					} else {
						// 重定向至订单详情
						uni.$emit("paySuccessTab")
						vk.redirectTo(`/pages/order/detail?_id=${this.oid}`)
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.app {
		padding: 20rpx;
	}

	.money {
		font-size: 30rpx;
		font-weight: bold;
		padding: 26rpx 20rpx;
		border-radius: 12rpx;
		background-color: #ffffff;
	}

	.type {
		margin: 20rpx 0;
		padding: 26rpx 20rpx 24rpx;
		border-radius: 12rpx;
		background-color: #ffffff;

		.logo {
			display: block;
			font-weight: bold;
			padding-bottom: 10rpx;
			font-size: 30rpx;
		}

		.item {
			display: flex;
			align-items: center;
			padding: 30rpx 0 10rpx 20rpx;

			.icon {
				width: 58rpx;
				height: 58rpx;
				margin-right: 18rpx;
			}

			.bal {
				color: #ff8f1e;
				font-size: 24rpx;
				margin-left: 10rpx;
			}

			.selt {
				width: 40rpx;
				height: 40rpx;
				margin-left: auto;
			}
		}
	}

	.btn {
		background-color: #24c388;
		border-radius: 44rpx;
		color: #ffffff;
		padding: 20rpx;
		text-align: center;
		margin-top: 240rpx;
		font-size: 30rpx;
	}

	/* 二维码支付弹窗开始 */
	.pay-qrcode-popup {
		position: fixed;
		width: 100vw;
		top: 0;
		bottom: 0;

		.pay-qrcode-popup-mask {
			position: absolute;
			top: 0;
			left: 0;
			width: 100vw;
			height: 100vh;
			background-color: rgba(0, 0, 0, 0.6);
		}

		.pay-qrcode-popup-content {
			position: relative;
			width: 500rpx;
			margin: 40% auto 0 auto;
			background-color: #ffffff;
			border-radius: 10rpx;
			padding: 40rpx;
			box-sizing: content-box;
			text-align: center;

			.pay-qrcode-popup-info {
				text-align: center;
				padding: 20rpx;

				.pay-qrcode-popup-info-fee {
					color: red;
					font-size: 60rpx;
					font-weight: bold;
				}
			}
		}
	}
</style>